package cn.yikaojiuguo.student.app;

import android.app.Application;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.xutils.DbManager;
import org.xutils.db.DbManagerImpl;
import org.xutils.x;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.bean.User;
import cn.yikaojiuguo.student.support.simple.ArgsConstants;
import cn.yikaojiuguo.student.support.utils.LogUtil;
import cn.yikaojiuguo.student.support.utils.Util;
import cn.yikaojiuguo.student.support.volley.RequestQueue;
import cn.yikaojiuguo.student.support.volley.toolbox.Volley;

/**
 * Created by cfan_yang on 2015/12/7.
 */
public class YiKaoApplication extends Application {

    //正式打包前，将该值改方false
    public static final boolean DEBUG_MOD = true;
    public static final int MAX_UPLOAD_IMG_SIZE = 300;
    public static final int MAX_UPLOAD_IMG_DES = 1000;
    private static final String TAG = "YiKaoApplication";
    private static YiKaoApplication mInstance;
    private static RequestQueue mRequestQueue;
    private static SharedPreferences mSharedPreferences = null;
    private static SharedPreferences.Editor mEditor = null;
    private static DbManager mCacheDbManager = null;
    private static String cacheFilePath = "";
    private static String cacheImgPath = "";
    private static String cacheVoicePath = "";

    // 微信APPID
    public static final String APP_ID = "wxc8c5f0de7e6f52a6";
    // 微信商户号
    public static final String MCH_ID = "1237752602";
    // 微信API密钥，在商户平台设置
    public static final String API_KEY = "546B81028427A64421F7B0691D0AB32D";
    private static IWXAPI msgApi;
    private final static int SET_ALIAS_FAILED = 1;
    private static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SET_ALIAS_FAILED:
                    setAliasAndTags(getUserId());
                    break;
            }
        }
    };;

    @Override
    public void onCreate() {
        super.onCreate();
        //多进程会导致Applicaton的onCreate多次调用，所有初始化操作放在该方法中执行
        mInstance = this;
        init();
    }

    private void init() {
        if (Util.getProcessName(android.os.Process.myPid()).equals(getPackageName())) {

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            {//SD卡存在,缓存等相关文件创建在SD卡
                File SD_CACHE_DIR = new File(ArgsConstants.SD_DIR + ArgsConstants.CACHE_DIR);
                if (!SD_CACHE_DIR.exists()) {
                    SD_CACHE_DIR.mkdirs();
                }
                cacheFilePath = SD_CACHE_DIR.getAbsolutePath();
                File IMG_CACHE = new File(cacheFilePath + "/image/");
                if(!IMG_CACHE.exists()) {
                    IMG_CACHE.mkdirs();
                }
                cacheImgPath = IMG_CACHE.getAbsolutePath();
                File VOICE_CACHE = new File(cacheFilePath + "/voice/");
                if(!VOICE_CACHE.exists()) {
                    VOICE_CACHE.mkdirs();
                }
                cacheVoicePath = VOICE_CACHE.getAbsolutePath();
            } else {//SD卡不存在，缓存等相关文件创建在/data目录下
                File DATA_CACHE_DIR = new File(ArgsConstants.DATA_DIR + ArgsConstants
                        .PACKAGE_NAME + ArgsConstants.CACHE_DIR);
                if (!DATA_CACHE_DIR.exists()) {
                    DATA_CACHE_DIR.mkdirs();
                }
                cacheFilePath = DATA_CACHE_DIR.getAbsolutePath();
                File IMG_CACHE = new File(cacheFilePath + "/image/");
                if(!IMG_CACHE.exists()) {
                    IMG_CACHE.mkdirs();
                }
                cacheImgPath = IMG_CACHE.getAbsolutePath();
                File VOICE_CACHE = new File(cacheFilePath + "/voice/");
                if(!VOICE_CACHE.exists()) {
                    VOICE_CACHE.mkdirs();
                }
                cacheVoicePath = VOICE_CACHE.getAbsolutePath();
            }
            //友盟统计,默认的页面统计方式
            MobclickAgent.openActivityDurationTrack(true);

            //初始化xUtils3
            x.Ext.init(this);
            x.Ext.setDebug(DEBUG_MOD);

            //创建Volley的RequestQueue
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

            //初始化SharedPreferences
            mSharedPreferences = getSharedPreferences(ArgsConstants.USER_INFO, MODE_PRIVATE);
            mEditor = mSharedPreferences.edit();

            //初始化缓存数据库
            DbManager.DaoConfig daoConfig = new DbManager.DaoConfig();
            daoConfig.setDbName(ArgsConstants.DB_CACHE_NAME);
            daoConfig.setDbDir(new File(ArgsConstants.DB_CACHE_DIR));
            mCacheDbManager = DbManagerImpl.getInstance(daoConfig);

            //初始化ImageLoader
            File cacheDir = StorageUtils.getOwnCacheDirectory(this, ArgsConstants.CACHE_DIR +
                    "imageloader/");
            DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory
                    (true).cacheOnDisk(true).considerExifParams(true).imageScaleType
                    (ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).displayer(new
                    FadeInBitmapDisplayer(100)).resetViewBeforeLoading(true).showImageOnLoading(R
                    .drawable.image_default).showImageForEmptyUri(R.drawable.image_default)
                    .showImageOnFail(R.drawable.image_default).build();
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                    .denyCacheImageMultipleSizesInMemory().diskCache(new UnlimitedDiskCache(cacheDir))
                    .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                    .defaultDisplayImageOptions(defaultOptions)
                    .tasksProcessingOrder(QueueProcessingType.LIFO).build();
            com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);

            //初始化微信
            msgApi = WXAPIFactory.createWXAPI(this, null);
            msgApi.registerApp(APP_ID);

            JPushInterface.setDebugMode(true);
            JPushInterface.init(this);
            setAliasAndTags(getUserId());
        }
    }

    public static IWXAPI getWXAPI() {
        return msgApi;
    }

    public static String getCacheFilePath() {
        return cacheFilePath;
    }

    public static String getCacheImgPath() {
        return cacheImgPath;
    }

    public static String getCacheVoicePath() {
        return cacheVoicePath;
    }

    /**
     * 设置极光推送的别名与标签，未登录状态要清空
     * @param alias
     */
    public static void setAliasAndTags(String alias) {

        if(TextUtils.isEmpty(alias)) { //未登录
            //清空之前的数据
            JPushInterface.setAliasAndTags(getInstance(), "", new HashSet<String>(0), new
                    TagAliasCallback() {

                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    if (i == 0) {
                        LogUtil.showInfoLog("JPush", "clear alias & tags success");
                    } else {
                        LogUtil.showErrorLog("JPush", "clear alias & tags failed");
                        mHandler.sendEmptyMessageDelayed(SET_ALIAS_FAILED,1000);
                    }
                }
            });
        } else {//已登录
            Set<String> targetSet = new HashSet<String>();
            targetSet.add(YiKaoApplication.getMajorName());
            targetSet.add("student");
            targetSet.add("android");
            JPushInterface.setAliasAndTags(getInstance(), alias, targetSet, new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    if (i == 0) {
                        LogUtil.showInfoLog("JPush", "set alias & tags success");
                    } else {
                        LogUtil.showErrorLog("JPush", "set alias & tags failed" + "i=" + i);
                        mHandler.sendEmptyMessageDelayed(SET_ALIAS_FAILED, 1000);
                    }
                }
            });
        }
    }

    /**
     * 保存用户名
     */
    public static void putUserName(String userName) {
        mEditor.putString(ArgsConstants.USER_NAME,userName).commit();
    }

    /**
     * 保存金币数量
     */
    public static void putGoldCoinNum(String num) {
        mEditor.putString(ArgsConstants.GOLD_COIN_NUM,num).commit();
    }

    /**
     * 修改用户信息缓存状态
     */
    public static void putUserInfoCacheState(boolean state) {
        mEditor.putBoolean(ArgsConstants.IS_USER_INFO_CACHE, state).commit();
    }

    /**
     * 保存用户头像
     */
    public static void putUserAvatar(String url) {
        mEditor.putString(ArgsConstants.USER_AVATAR, url).commit();
    }

    /**
     * 保存 secretkey(token)
     */
    public static void putSecretkey(String key) {
        mEditor.putString(ArgsConstants.SECRETKEY, key).commit();
    }

    /**
     * 保存用户ID
     */
    public static void putUserId(String id) {
        mEditor.putString(ArgsConstants.USER_ID, id).commit();
    }

    /**
     * 保存省份ID（接口返回为String类型）
     */
    public static void putProvinceId(String id) {
        mEditor.putString(ArgsConstants.PROVINCE_ID, id).commit();
    }

    /**
     * 保存省份名称
     */
    public static void putProvinceName(String name) {
        mEditor.putString(ArgsConstants.PROVINCE_NAME, name).commit();
    }

    /**
     * 保存验证码
     */
    public static void putCaptcha(String code) {
        mEditor.putString(ArgsConstants.CAPTCHA, code).commit();
    }

    /**
     * 保存年级ID（接口返回为String类型）
     */
    public static void putGradeId(String id) {
        mEditor.putString(ArgsConstants.GRADE_ID, id).commit();
    }

    /**
     * 保存专业分类ID（接口返回为String类型）
     */
    public static void putMajorId(String id) {
        mEditor.putString(ArgsConstants.MAJOR_ID, id).commit();
    }

    /**
     * 保存专业分类名称
     */
    public static void putMajorName(String name) {
        mEditor.putString(ArgsConstants.MAJOR_NAME, name).commit();
    }

    /**
     * 存储登录的手机号码
     */
    public static void putMobileNumber(String number) {
        mEditor.putString(ArgsConstants.MOBILE_NUMBER, number).commit();
    }

    /**
     * 存储专业索引，从0开始
     */
    public static void putChooseMajorIndex(int index) {
        mEditor.putInt(ArgsConstants.CHOOSE_MAJOR, index).commit();
    }

    /**
     * 存储年级索引，从0开始,若要对应年级ID需加1
     */
    public static void putChooseGradeIndex(int index) {
        mEditor.putInt(ArgsConstants.CHOOSE_GRADE, index).commit();
    }

    /**
     * 保存年级名称
     */
    public static void putGradeName(String name) {
        mEditor.putString(ArgsConstants.GRADE_NAME, name).commit();
    }

    /**
     * 得到 secretkey(token)
     */
    public static String getSecretkey() {
        return mSharedPreferences.getString(ArgsConstants.SECRETKEY, "");
    }

    public static DbManager getCacheDbManager() {
        return mCacheDbManager;
    }

    public static void setCacheDbManager(DbManager dbManager) {
        mCacheDbManager = dbManager;
    }

    public static YiKaoApplication getInstance() {
        return mInstance;
    }

    /**
     * 获取Volley的RequestQueue
     */
    public static RequestQueue getRequestQueue() {
        return mRequestQueue;
    }

    /**
     * 获取专业选择索引
     */
    public static int getChooseMajorIndex() {
        return mSharedPreferences.getInt(ArgsConstants.CHOOSE_MAJOR, -1);
    }

    /**
     * 获取年级选择索引
     */
    public static int getChooseGradeIndex() {
        return mSharedPreferences.getInt(ArgsConstants.CHOOSE_GRADE, -1);
    }

    /**
     * 获取登录的手机号码
     */
    public static String getMobileNubmer() {
        return mSharedPreferences.getString(ArgsConstants.MOBILE_NUMBER, "");
    }

    /**
     * 是否第一次安装或更新后第一次启动
     */
    public static boolean isFirstStart() {
        int oldVersionCode = mSharedPreferences.getInt(ArgsConstants.VERSIONG_CODE, 0);
        int currentVersionCode = Util.getVersionCode();
        if (oldVersionCode != currentVersionCode) {
            return true;
        }
        return false;
    }

    /**
     * 设置状态为已经启动过
     */
    public static void haveStarted() {
        mEditor.putInt(ArgsConstants.VERSIONG_CODE, Util.getVersionCode()).commit();
    }

    /**
     * 获取专业分类ID,"0"为获取失败
     */
    public static String getMajorId() {
        return mSharedPreferences.getString(ArgsConstants.MAJOR_ID, "0");
    }

    /**
     * 获取专业分类名称
     */
    public static String getMajorName() {
        return mSharedPreferences.getString(ArgsConstants.MAJOR_NAME, "");
    }

    /**
     * 获取专业分类ID,"0"为获取失败
     */
    public static String getGradeId() {
        return mSharedPreferences.getString(ArgsConstants.GRADE_ID, "0");
    }

    /**
     * 获取年级名称
     */
    public static String getGradeName() {
        return mSharedPreferences.getString(ArgsConstants.GRADE_NAME, "");
    }

    /**
     * 获取省份ID,"0"为获取失败
     */
    public static String getProvinceId() {
        return mSharedPreferences.getString(ArgsConstants.PROVINCE_ID, "0");
    }

    /**
     * 获取省份名称
     */
    public static String getProvinceName() {
        return mSharedPreferences.getString(ArgsConstants.PROVINCE_NAME, "");
    }

    /**
     * 获取验证码
     */
    public static String getCaptcha() {
        return mSharedPreferences.getString(ArgsConstants.CAPTCHA, "");
    }

    /**
     * 获取用户ID,如果没有登录返回空字符串
     */
    public static String getUserId() {
        return mSharedPreferences.getString(ArgsConstants.USER_ID,"");
    }

    /**
     * 获取用户头像
     */
    public static String getUserAvatar() {
        return mSharedPreferences.getString(ArgsConstants.USER_AVATAR,"");
    }

    /**
     * 返回金币数量
     */
    public static String getGoldCoinNum() {
        return mSharedPreferences.getString(ArgsConstants.GOLD_COIN_NUM,"0");
    }

    /**
     * 获取用户名
     */
    public static String getUserName() {
        return mSharedPreferences.getString(ArgsConstants.USER_NAME,"");
    }

    /**
     * 获取SDK版本号
     */
    public static int getSDKVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * 通过user id来判断是否登录
     */
    public static boolean isLogin() {
        if(TextUtils.isEmpty(getUserId())) {
            return false;
        }
        return true;
    }

    /**
     * 登录成功，退出登录时调用，清空用户信息缓存数据
     */
    public static void clearCacheUserInfo() {
        //清空 user id
        putUserId("");
        //清空token
        putSecretkey("");
        //清空省份名称和id
        putProvinceName("");
        putProvinceId("0");
        //清空专业名称和id
        putMajorName("");
        putMajorId("0");
        //清空年级名称和id
        putGradeName("");
        putGradeId("0");
        //清空用户头像
        putUserAvatar("");
        //清空手机号
        putMobileNumber("");
        //清空金币
        putGoldCoinNum("0");
        putUserName("");
        putUserSex("0");
        putUserBirth("");
        putUserInfoCacheState(false);
    }

    /**
     * 保存用户信息
     */
    public static void putUserInfo(User user) {
        putUserId(user.id);
        putProvinceName(user.provincename);
        putProvinceId(user.province);
        putMajorName(user.categoryname);
        putMajorId(user.category);
        putGradeName(user.gradename);
        putGradeId(user.grade);
        putUserAvatar(user.litpic);
        putMobileNumber(user.mobile);
        putGoldCoinNum(user.gold);
        putUserName(user.username);
        putUserSex(user.sex);
        putUserInfoCacheState(true);
        putUserBirth(user.birthday);
        changeUserInfoCache(true);
    }

    /**
     * 返回是否缓存了用户信息
     */
    public static boolean isUserInfoCache() {
        return mSharedPreferences.getBoolean(ArgsConstants.IS_USER_INFO_CACHE,false);
    }

    /**
     * 返回用户缓存数据是否发生了变化
     */
    public static boolean isUserInfoCacheChanged() {
        return mSharedPreferences.getBoolean(ArgsConstants.IS_USER_INFO_CACHE_CHANGED,false);
    }

    /**
     * 用户缓存数据发生了变化
     */
    public static void changeUserInfoCache(boolean changed) {
        mEditor.putBoolean(ArgsConstants.IS_USER_INFO_CACHE_CHANGED,changed).commit();
    }

    /**
     * 保存上传图片文件的文件名
     */
    public static void putUploadImgName(String name) {
        mEditor.putString(ArgsConstants.UPLOAD_IMG_NAME, name).commit();
    }

    /**
     * 获取上传图片文件的文件名
     */
    public static String getUploadImgName() {
        return mSharedPreferences.getString(ArgsConstants.UPLOAD_IMG_NAME,"");
    }

    /**
     * 保存用户性别
     * @param sex 0不显示 1男 2女
     */
    public static void putUserSex(String sex) {
        mEditor.putString(ArgsConstants.USER_SEX,sex).commit();
    }

    /**
     * 保存用户性别
     * 0不显示 1男 2女
     */
    public static int getUserSex() {
        int sex = Integer.parseInt(mSharedPreferences.getString(ArgsConstants.USER_SEX,"0"));
        return sex;
    }

    /**
     * 保存用户生日
     */
    public static void putUserBirth(String birth) {
        mEditor.putString(ArgsConstants.USER_BIRTH,birth).commit();
    }

    /**
     * 获取用户生日
     */
    public static String getUserBirth() {
        return mSharedPreferences.getString(ArgsConstants.USER_BIRTH,"");
    }

    /**
     * 保存选择省份的索引
     */
    public static void putChoseProvinceIndex(int index) {
        mEditor.putInt(ArgsConstants.CHOOSE_PROVINCE,index).commit();
    }

    /**
     * 获取选择省份的索引
     */
    public static int getChooseProvinceIndex() {
        return mSharedPreferences.getInt(ArgsConstants.CHOOSE_PROVINCE,-1);
    }

    /**
     * 设置消息声音状态
     */
    public static void putMessageSoundState(boolean state) {
        mEditor.putBoolean(ArgsConstants.MESSAGE_SOUND_STATE,state).commit();
    }

    /**
     * 获得消息声音状态
     */
    public static boolean getMessageSoundState() {
        return mSharedPreferences.getBoolean(ArgsConstants.MESSAGE_SOUND_STATE,true);
    }

    /**
     * 设置消息振动状态
     */
    public static void putMessageVibrateState(boolean state) {
        mEditor.putBoolean(ArgsConstants.MESSAGE_VIBRATE_STATE,state).commit();
    }

    /**
     * 获得消息振动状态
     */
    public static boolean getMessageVibrateState() {
        return mSharedPreferences.getBoolean(ArgsConstants.MESSAGE_VIBRATE_STATE,true);
    }
}
